package com.choosefine.it.common.aop;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by 邱鹏 on 12/23/15.
 */
@Aspect            //定义一个切面
@Configuration
public class AppFirewall {
    private static final Logger logger = LoggerFactory.getLogger("api service v1");
    ObjectMapper mapper = new ObjectMapper();
//    @Autowired
//    RedisTemplate redisTemplate;

    /**
     * 定义切点Pointcut  * com.xyz.service..*.*(..)
     */
    @Pointcut(value = "@annotation(org.springframework.web.bind.annotation.GetMapping))&&execution(public * com.choosefine.shopping..*.*Controller.*(..)")
    public void isAllowedIp() {
    }

    /**
     * 处理拦截到接口访问请求，判断是否允许
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around(value = "isAllowedIp()")
    public Object doAroundIsAllowedIp(ProceedingJoinPoint pjp) throws Throwable {
        logger.info("-----------------------对--切--点--进--行--事--前--拦--截--------------------------------");
        Object result = null;
        Boolean isAllow = false;
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();//获取request
        String remoteIP = request.getRemoteAddr();//访问者的ip
        String thisMethod = pjp.getSignature().getName();//当前函数的名称
        /*参照：com.pjbao.apiService.common.controller.ApiController.listAllIP*/
        String fullName = pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName();
        //获取目标对象对应的类名
//        logger.info("应用注解的类名：" + pjp.getTarget().getClass());
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
//        logger.info("获取到的方法的具体参数值：" + method.getName());
        Object[] args = pjp.getArgs();//被拦截方法的所有参数
        //分页检查
        List paramList = new ArrayList();
        String token = request.getParameter("token");
        logger.info("##############当前用户的访问ip是：" + remoteIP);

        result = pjp.proceed();
        logger.info("--->--->--->--->--->  执行完毕进行的收尾工作  <---<---<---<---<---<---");
        return result;
    }
}